package com;

import lombok.extern.slf4j.Slf4j;
import org.glassfish.jersey.internal.util.Base64;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.Principal;

/**
 * 获取request的filter
 */
@PreMatching
@Slf4j
public class RequestFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        //获取请求的参数
       log.info ("Executing REST RequestFilter getAbsolutePath >"+requestContext.getUriInfo().getAbsolutePath());
       log.info("Executing REST RequestFilter header >"+requestContext.getUriInfo().getPath());
       log.info("Executing REST RequestFilter getMethod >"+requestContext.getMethod());
       //此处测试
      /*  final Charset CHARACTER_SET = Charset.forName("utf-8");
        String authHeader = requestContext.getHeaders().getFirst( HttpHeaders.AUTHORIZATION);
        log.info ( "authHeader={}",authHeader );
        if (authHeader != null && authHeader.startsWith("Basic")) {
            String decoded = new String( Base64.decode(authHeader.toString ().getBytes()), CHARACTER_SET);
//                  String decoded = Base64.decodeAsString(authHeader.substring(6));
            final String[] split = decoded.split(":");
            final String username = split[0];
            //log.info (  );
            final String pwd = split[0];
            log.info ( "pwd={}",pwd );
            if (pwd.equals(pwd)) {//这里做了最大简化
                requestContext.setSecurityContext(new SecurityContext () {
                    @Override
                    public Principal getUserPrincipal() {
                        return new Principal() {
                            @Override
                            public String getName() {
                                return username;
                            }
                        };
                    }

                    @Override
                    public boolean isUserInRole(String role) {
                        return true;
                    }

                    @Override
                    public boolean isSecure() {
                        return false;
                    }

                    @Override
                    public String getAuthenticationScheme() {
                        return "BASIC";
                    }
                });
                return;
            }
        }
        requestContext.abortWith( Response.status(401).header(HttpHeaders.WWW_AUTHENTICATE, "Basic").build())*/;

    }



}
